<template>
	<view class="container">
		<!-- 顶部问候语和头像部分 -->
		<view class="header-section">
			<text class="greeting">你好！{{teacherName}}</text>
			<image class="avatar" :src="teacherUrls"></image>
		</view>

		<!-- 搜索框单独一行 -->
		<view class="calendar-search-row">
			
			<!-- 详细搜索表单 -->
			<view class="detailed-search-form" >
				
				<view class="date-input-row">
					<view class="date-input" @click="showDatePicker = true" style="cursor:pointer;">
						日期   {{ selectedDate ? selectedDate : '请选择日期' }}
					</view>
					<u-icon size="30" name="calendar" color="#999" @click="showDatePicker = true"></u-icon>
				</view>
				
			</view>
		</view>
		<!-- 日期/周导航部分 -->
		<view class="week-navigation-section" v-show="!showDetailedSearch">
			<text class="nav-arrow" @click="goToPreviousWeek">＜ 上一周</text>
			<view class="date-display">
				<text class="current-date">{{formatWeekRange}}</text>
			</view>
			<text class="nav-arrow" @click="goToNextWeek">下一周 ＞</text>
		</view>

		<!-- 星期和日期网格 -->
		<view class="day-grid-section" v-show="!showDetailedSearch">
			<view class="weekday-header">
				<text v-for="day in weekdays" :key="day">{{day}}</text>
			</view>
			<view class="day-numbers">
				<text 
					v-for="(day, index) in calendarDays" 
					:key="index"
					:class="{
						'day-number': true,
						'today-unselected': day.isToday && selectedFullDate !== day.fullDate,
						'selected': selectedFullDate === day.fullDate
					}"
					@click="selectCalendarDay(day)"
				>
					{{ day.isToday ? '今' : day.day }}
				</text>
			</view>
		</view>

		<!-- 课程列表 -->
		<view class="course-list-section">
			<view class="course-card" v-for="(lesson, index) in selectedDayLessonDetails" :key="index">
				<view class="time-display">
					<text class="time-icon">🕒</text>
					<text class="time-range">{{lesson.timePeriod}}</text>
				</view>
				<text class="course-name">课程：{{lesson.courseName}}</text>
				<text class="class-name">班级：{{lesson.claDescribe}}</text>
			</view>
			<view class="course-card" v-if="selectedDayLessonDetails.length === 0">
				<view class="time-display">
					<text class="time-icon">🕒</text>
					<text class="time-range">无课程</text>
				</view>
				<text class="course-name">今日无课程</text>
				<text class="class-name"></text>
			</view>
		</view>

		<!-- 底部导航栏 -->
		<tabBar></tabBar>

		<!-- 在template底部补充日期选择器组件 -->
		<u-datetime-picker
			:show="showDatePicker"
			mode="date"
			@confirm="confirmDate"
			@cancel="showDatePicker = false"
			:value="new Date(selectedDate).getTime()"
		></u-datetime-picker>
	</view>
</template>

<script>
	import {teacherDate,teacherUrl} from "@/api/schedule.js"
	export default {
		data() {
			const today = new Date();
			// 获取当前周的起始日期 (周一)
			const dayOfWeek = today.getDay(); // 周日 - 0, 周一 - 1, ..., 周六 - 6
			const diff = today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1); // 调整到周一
			const weekStartDate = new Date(today.setDate(diff));
			
			const weekEndDate = new Date(weekStartDate);
			weekEndDate.setDate(weekStartDate.getDate() + 6);

			const todayStr = uni.$u.timeFormat(today, 'yyyy-mm-dd');

			return {
				teacherName:'',
				teacherUrls:'',
				currentWeekStartDate: weekStartDate,
				currentWeekEndDate: weekEndDate,
				showDetailedSearch: false,
				currentWeekLessons: [], // 存储当前周的课程数据
				selectedFullDate: null, // 日历中选中的日期对象的 fullDate 字符串
				selectedDayLessonDetails: [], // 选中日期的课程详情列表
				weekdays: ['一', '二', '三', '四', '五', '六', '日'],
				calendarDays: [], // 用于日历网格所有日期的数组
				showDatePicker: false,
				selectedDate: todayStr // 初始化为今天
			}
		},
		computed: {
			formatWeekRange() {
				// 如果有选中的日期，显示选中的日期，否则显示今天
				let dateStr = this.selectedFullDate;
				if (!dateStr) {
					dateStr = uni.$u.timeFormat(new Date(), 'yyyy-mm-dd');
				}
				return dateStr;
			}
		},
		onLoad() {
			this.fetchLessonsForWeek(this.currentWeekStartDate, this.currentWeekEndDate);
			const data = {
				teacherId:uni.getStorageSync('userId')
			}
			//给老师头像赋值
			teacherUrl(data).then(res => {
				console.log(res)
				if(res.data.teacher.avatar != ''){
					this.teacherUrls = res.data.teacher.avatar
				}
				if(res.data.teacher.userName != ''){
					this.teacherName = res.data.teacher.nick_name
				}
				
			}).catch(err => {
				uni.showToast({
					title: '查询头像失败',
					icon: 'error'
				});
				console.log(err);
			}
			)
		},
		methods: {
			//点击查询搜索课程
			inquire(){
				console.log(this.selectedDate);
				console.log(uni.getStorageSync('userId'));
				const data = {
					date:this.selectedDate,
					teacherId:uni.getStorageSync('userId')
				}
				//调用api查询课程
				teacherDate(data).then(res => {
					console.log(res);
					this.selectedDayLessonDetails = res.data.teacherCourse
				}).catch(error=>{
					uni.showToast({
						title: '查询课程失败',
						icon: 'error'
					});
					console.log(error);
				})
			},
			toggleDetailedSearch: function() {
				this.showDetailedSearch = !this.showDetailedSearch;
			},
			// 模拟从数据库获取课程数据
			fetchLessonsForWeek(startDate, endDate) {
				// 假设这是从服务器获取的数据
				const mockLessons = [
					{ date: '2025-06-09', time: '09:00-12:00', course: '书法基础', class: 'C班' },
					{ date: '2025-06-09', time: '14:00-17:00', course: '国画入门', class: 'A班' },
					{ date: '2025-06-10', time: '08:00-11:00', course: '少儿绘画课', class: 'A班' },
					{ date: '2025-06-10', time: '14:00-17:00', course: '少儿绘画课', class: 'B班' },
					{ date: '2025-06-12', time: '10:00-13:00', course: '油画进阶', class: 'B班' }
				];

				// 过滤出当前周的课程
				this.currentWeekLessons = mockLessons.filter(lesson => {
					const lessonDate = new Date(lesson.date);
					return lessonDate >= startDate && lessonDate <= endDate;
				});
				this.selectedFullDate = null; // 重置选中日期，避免旧周引用问题
				this.selectedDayLessonDetails = []; // 重置课程详情
				this.generateWeekDays(); // 获取课程后重新生成周日期
				this.selectInitialDay(); // 首次加载或切换周后，默认选中今天或第一个有课的日期
			},

			generateWeekDays() {
				this.calendarDays = [];
				const today = new Date();
				const currentDayFullDate = uni.$u.timeFormat(today, 'yyyy-mm-dd');

				for (let i = 0; i < 7; i++) {
					const day = new Date(this.currentWeekStartDate);
					day.setDate(this.currentWeekStartDate.getDate() + i);
					const fullDate = uni.$u.timeFormat(day, 'yyyy-mm-dd');
					const isToday = fullDate === currentDayFullDate;
					const hasLesson = this.currentWeekLessons.some(lesson => lesson.date === fullDate);
					
					this.calendarDays.push({
						day: day.getDate(),
						fullDate: fullDate,
						isToday: isToday,
						hasLesson: hasLesson
					});
				}
			},

			selectCalendarDay(dayObj) {
				console.log(dayObj.fullDate);
				// 只需设置当前选中的日期对象的 fullDate 字符串
				this.selectedFullDate = dayObj.fullDate;
				//session拿到老师id
				console.log(uni.getStorageSync('userId'));
				const data = {
					date:dayObj.fullDate,
					teacherId:uni.getStorageSync('userId')
				}
				//调用api查询课程
				teacherDate(data).then(res => {
					console.log(res);
					this.selectedDayLessonDetails = res.data.teacherCourse
				}).catch(error=>{
					uni.showToast({
						title: '查询课程失败',
						icon: 'error'
					});
					console.log(error);
				})
					
				// 过滤出选中日期的课程
				//this.selectedDayLessonDetails = this.currentWeekLessons.filter(lesson => lesson.date === dayObj.fullDate);
				
				
			},

			selectInitialDay() {
				const todayFullDate = uni.$u.timeFormat(new Date(), 'yyyy-mm-dd');
				const todayDay = this.calendarDays.find(day => day.fullDate === todayFullDate);
				
				if (todayDay) {
					// 如果今天在当前周内，选中今天
					this.selectCalendarDay(todayDay);
				} else if (this.calendarDays.length > 0) {
					// 如果今天不在当前周，则选中当前周的第一天
					this.selectCalendarDay(this.calendarDays[0]);
				}
			},

			goToPreviousWeek() {
				this.showDetailedSearch = false; // 切换周时收起搜索框
				const newStartDate = new Date(this.currentWeekStartDate);
				newStartDate.setDate(newStartDate.getDate() - 7);
				const newEndDate = new Date(this.currentWeekEndDate);
				newEndDate.setDate(newEndDate.getDate() - 7);
				this.currentWeekStartDate = newStartDate;
				this.currentWeekEndDate = newEndDate;
				this.fetchLessonsForWeek(this.currentWeekStartDate, this.currentWeekEndDate);
			},

			goToNextWeek() {
				this.showDetailedSearch = false; // 切换周时收起搜索框
				const newStartDate = new Date(this.currentWeekStartDate);
				newStartDate.setDate(newStartDate.getDate() + 7);
				const newEndDate = new Date(this.currentWeekEndDate);
				newEndDate.setDate(newEndDate.getDate() + 7);
				this.currentWeekStartDate = newStartDate;
				this.currentWeekEndDate = newEndDate;
				this.fetchLessonsForWeek(this.currentWeekStartDate, this.currentWeekEndDate);
			},

			confirmDate(e) {
				this.selectedDate = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
				this.showDatePicker = false;
				// 解析选择的日期
				const selected = new Date(this.selectedDate);
				// 计算该日期所在周的周一
				const dayOfWeek = selected.getDay(); // 周日-0, 周一-1, ..., 周六-6
				const diff = selected.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1);
				const weekStartDate = new Date(selected);
				weekStartDate.setDate(diff);
				const weekEndDate = new Date(weekStartDate);
				weekEndDate.setDate(weekStartDate.getDate() + 6);
				// 用时间戳判断是否同一周
				const curStart = new Date(this.currentWeekStartDate.getFullYear(), this.currentWeekStartDate.getMonth(), this.currentWeekStartDate.getDate()).getTime();
				const newStart = new Date(weekStartDate.getFullYear(), weekStartDate.getMonth(), weekStartDate.getDate()).getTime();
				if (curStart !== newStart) {
					this.currentWeekStartDate = weekStartDate;
					this.currentWeekEndDate = weekEndDate;
					this.fetchLessonsForWeek(this.currentWeekStartDate, this.currentWeekEndDate);
					setTimeout(() => {
						const day = this.calendarDays.find(d => d.fullDate === this.selectedDate);
						if (day) {
							this.selectCalendarDay(day);
						}
					}, 0);
				} else {
					// 当前周，直接高亮
					const day = this.calendarDays.find(d => d.fullDate === this.selectedDate);
					if (day) {
						this.selectCalendarDay(day);
					}
				}
			}
		}
	}
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
		font-family: Arial, sans-serif;
	}

	/* 顶部问候语和头像部分 */
	.header-section {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #2C57F6;
		padding: 20px 15px;
		color: #fff;
		border-radius: 0 0 15px 15px;
	}

	.greeting {
		font-size: 20px;
		font-weight: bold;
	}

	.avatar {
		width: 60px;
		height: 60px;
		border-radius: 50%;
		border: 2px solid #fff;
	}
	
	.calendar-search-row {
		display: flex;
		justify-content: center;
		margin-top: 24px;
		margin-bottom: 18px;
		padding: 0;
		width: 100%;
	}
	.search-box {
		display: flex;
		color: #4296E5;
		font-size: 17px;
		font-weight: 700;
		align-items: center;
		background-color: #F5F5F5;
		border-radius: 20px;
		padding: 5px 10px;
	}
	.search-text {
		margin-right: 5px;
	}
	.date-input-row {
		display: flex;
		align-items: center;
		border: 1px solid #eee;
		border-radius: 8px;
		border-radius: 5px;
		padding: 8px 10px;
		margin-bottom: 15px;
	}
	.date-label {
		color: #666;
		margin-right: 10px;
		font-size: 14px;
	}
	.date-input {
		flex: 1;
		border: none;
		outline: none;
		font-size: 14px;
		color: #333;
	}
	.buttons-row {
		display: flex;
		justify-content: space-around;
		gap: 15px;
	}
	.reset-button,
	.query-button {
		flex: 1;
		padding: 5px 0;
		border-radius: 20px;
		font-size: 14px;
		font-weight: bold;
		border: none;
		outline: none;
		cursor: pointer;
	}
	
	.reset-button {
		background-color: #fff;
		color: #666;
		border: 1px solid #ddd;
	}
	
	.query-button {
		background-color: #4296E5;
		color: #fff;
	}

	/* 日期/周导航部分 */
	.week-navigation-section {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 8px 15px 8px 15px;
		font-size: 14px;
		color: #666;
	}

	.date-display {
		display: flex;
		align-items: center;
	}

	.current-date {
		font-weight: bold;
		color: #4296E5;
		font-size: 16px;
	}

	.nav-arrow {
		color: #4296E5;
	}

	/* 星期和日期网格 */
	.day-grid-section {
		background-color: #fff;
		margin: 0 15px 10px 15px;
		border-radius: 10px;
		padding: 12px;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
	}

	.weekday-header,
	.day-numbers {
		display: flex;
		justify-content: space-around;
		margin-bottom: 10px;
	}

	.weekday-header text,
	.day-number {
		width: 35px;
		height: 35px;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 13px;
		color: #333;
		position: relative;
	}

	.weekday-header text {
		color: #999;
	}

	.day-number.today-unselected {
		border-radius: 50%;
		border: 1px solid #4296E5;
		color: #4296E5;
		background-color: transparent;
	}

	.day-number.selected {
		background-color: #4296E5;
		color: #fff;
		border-radius: 50%;
	}

	/* 课程列表 */
	.course-list-section {
		margin: 0 15px 10px 15px;
		flex: 1; /* 允许课程列表占据可用空间 */
		overflow-y: auto; /* 如果内容溢出，启用滚动 */
	}

	.course-card {
		background-color: #fff;
		border-radius: 10px;
		padding: 15px;
		margin-bottom: 10px;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
	}

	.time-display {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
		font-size: 14px;
		color: #4296E5;
	}

	.time-icon {
		margin-right: 5px;
	}

	.course-name,
	.class-name {
		font-size: 15px;
		color: #333;
		margin-bottom: 5px;
		margin-right: 30px;
		text-align: left;
	}

	/* 底部导航栏 */
	.bottom-nav-bar {
		display: flex;
		justify-content: space-around;
		align-items: center;
		background-color: #fff;
		padding: 10px 0;
		border-top: 1px solid #eee;
		position: sticky; /* 如果内容滚动，使用 sticky 实现底部导航栏 */
		bottom: 0;
		width: 100%;
	}

	.nav-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 12px;
		color: #666;
	}

	.nav-item .icon {
		font-size: 22px;
		margin-bottom: 3px;
	}

	.nav-item.active {
		color: #4296E5; /* 选中导航项的激活颜色 */
	}

	/* 优化详细搜索表单样式 */
	.detailed-search-form {
		display: flex;
		flex-direction: column;
		background-color: transparent; /* 无背景色 */
		border-radius: 10px;
		padding: 0;
		width: 100%;
		margin: 0 auto;
		box-shadow: none;
		align-items: center;
	}
	.search-header {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
		font-size: 17px;
		font-weight: 700;
		color: #4296E5;
		justify-content: center; /* 居中 */
		width: 100%;
	}
	.date-input-row {
		display: flex;
		align-items: center;
		border: 1px solid #eee;
		border-radius: 6px;
		padding: 6px 8px;
		margin-bottom: 12px;
		background: #fff;
		width: 220px; /* 宽度缩小 */
		margin-left: auto;
		margin-right: auto;
	}
	.date-label {
		color: #666;
		margin-right: 8px;
		font-size: 14px;
	}
	.date-input {
		flex: 1;
		border: none;
		outline: none;
		font-size: 15px;
		color: #333;
		background: transparent;
	}
	.buttons-row {
		display: flex;
		justify-content: space-between;
		gap: 8px;
		margin-top: 0;
		width: 220px;
		margin-left: auto;
		margin-right: auto;
	}
	.reset-button,
	.query-button {
		flex: 1;
		padding: 6px 0;
		border-radius: 18px;
		font-size: 14px;
		font-weight: bold;
		border: none;
		outline: none;
		cursor: pointer;
		margin: 0;
	}
	.reset-button {
		background-color: #fff;
		color: #666;
		border: 1px solid #ddd;
	}
	.query-button {
		background-color: #4296E5;
		color: #fff;
	}
	/* 去掉三角形箭头 */
	.detailed-search-form::before {
		display: none;
	}
</style>
